﻿import com.gamepackage.events.*;
import com.gamepackage.util.Loadable;

class com.gamepackage.util.LoadClip
{
	static var LOADFAILED_TIMEOUT: Number = 500; //-- IN FRAMES
	
	private var loadable: Loadable;
	private var url: String;
	private var info: Object;
	
	private var loaderClip: MovieClip;
	
	private var loader: Thread;
	
	public var addListener: Function;
	public var removeListener: Function;
	private var broadcastMessage: Function;
	
	private var complete: Boolean;
	private var loading: Boolean;
	private var timeout: Number;
	
	function LoadClip( loadable: Loadable, url: String, info: Object )
	{
		this.loadable = loadable;
		this.url = url;
		this.info = info;
		
		complete = false;
		loading  = false;
		timeout  = LOADFAILED_TIMEOUT;
		
		loader = new Thread( this , trackClip );
		
		AsBroadcaster.initialize( this );
	}
	
	function load(): Void
	{
		broadcastMessage( 'onLoadClipRequest' , this );
		( loaderClip = loadable.getLoaderClip() ).loadMovie( url );
		loader.start();
	}
	
	function trackClip(): Void
	{
		var loaded: Number = loaderClip.getBytesLoaded();
		var total: Number  = loaderClip.getBytesTotal();
		
		if ( total > 0 )
		{
			if ( !loading )
			{
				broadcastMessage( 'onLoadClipStart' , this , total );
				loading = true;
				return;
			}
			else
			{
				broadcastMessage( 'onLoadClipProcess' , this , loaded , total );
			}
		}
		else if( !loading )
		{
			if ( --timeout < 0 )
			{
				broadcastMessage( 'onLoadClipFailed' , this );
				loader.stop();
				return;
			}
		}
		
		if ( complete )
		{
			if ( loaderClip._currentframe )
			{
				broadcastMessage( 'onLoadClipInit' , this );
				loader.stop();
				return;
			}
			return;
		}
		
		if ( loaded == total && loaded > 0 && !complete )
		{
			broadcastMessage( 'onLoadClipComplete' , this );
			complete = true;
			return;
		}
	}
	
	function getInfo( Void ): Object
	{
		return info;
	}
}



